using System;
using Flaschengeist.Entities;
using Flaschengeist.Views;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadLevel : MonoBehaviour
	{
		private LoadLevelInfo loadInfo;
		private ErrorView errorView;	
		
		public void Start()
		{				
			errorView = gameObject.GetComponent<ErrorView>();
			loadInfo = gameObject.AddComponent<LoadLevelInfo>();
			loadInfo.Completed += LoadCompleted;
		}
		
		private void LoadCompleted(Level lvl)
		{
			var calcTotalFluid = new CalculateTrackFluid(lvl.MaxFillLevel, lvl.Scale);
			var calcTotalTime = new CalculateTotalTime();
			calcTotalFluid.Completed += (totalFluid) => lvl.TotalFluid = totalFluid;	
			calcTotalTime.Completed += (totalTime) => lvl.TotalTimeSec = totalTime;
			calcTotalFluid.Process(lvl.Track);
			calcTotalTime.Process(lvl.Track);
			Completed(lvl);
		}	
		
		public void Process(int id)
		{		
			Debug.Log("Start load level " + id);
						
			try 
			{
				var level = new Level();
				level.Id = id;			
				loadInfo.Process(level);
			} 
			catch (Exception ex) 
			{
				errorView.Show(ex);
			}
		}
			
		public event Action<Level> Completed;	
	}
}


